package com.jinbao.springbootinit.controller;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 队列测试
 */
@RestController
@RequestMapping("/queue")
@Slf4j
@Profile({"dev","local"})
public class QueueController {
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/add")
    public void add(String name){
        //使用CompletableFuture,进行运行一个异步任务
        CompletableFuture.runAsync(()->{
            log.info(Thread.currentThread().getName()+"执行："+name);
            try {
                Thread.sleep(60*10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },threadPoolExecutor);
    }

    @GetMapping("get")
    public String get(){
        //创建一个HashMap存储线程的状态信息
        Map<String,Object> map=new HashMap<>();
        //获取线程池的长度
        int queueSize=threadPoolExecutor.getQueue().size();
        //加入map
        map.put("队列长度",queueSize);
        //获取线程池的已接任务总数
        long taskCount=threadPoolExecutor.getTaskCount();
        map.put("已接任务数",taskCount);
        //获取线程已完成的任务数
        long completedTaskCount=threadPoolExecutor.getCompletedTaskCount();
        map.put("已完成的任务数",completedTaskCount);
        //获取正在执行的任务线程数
        int activeCount=threadPoolExecutor.getActiveCount();
        map.put("现在在执行的任务数",activeCount);

        //map转化为Json返回
        return JSONUtil.toJsonStr(map);






    }





}
